﻿#if UNITY_EDITOR

using System.Diagnostics;
using UnityEngine;

namespace BF
{
    public class CommandUtil
    {
        public class Result
        {
            public int code;
            public string output;
            public string error;

            public Result(Process process) 
                : this(process.ExitCode, process.StandardOutput.ReadToEnd(), process.StandardError.ReadToEnd())
            {

            }

            public Result(int code, string output, string error)
            {
                this.code = code;
                this.output = output;
                this.error = error;
            }

            public override string ToString()
            {
                return $"{code} ---- {output} ---- {error}";
            }
        }

        [System.Obsolete("Use CommandUtil.Execute instead", false)]
        public static Result ExecuteCommand(string command)
        {
            return Execute(command);
        }

        public static Result Execute(string command)
        {
            command = command.Replace("\"", "\\\"");

            ProcessStartInfo processInfo = null;

            switch (Application.platform)
            {
                case RuntimePlatform.OSXEditor:
                    processInfo = new ProcessStartInfo("/bin/bash", $"-c \"{command}\"");
                    break;
                case RuntimePlatform.WindowsEditor:
                    processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
                    break;
                default:
                    UnityEngine.Debug.LogError($"Not support platform: {Application.platform}");
                    return new Result(-1, "execute error", $"Not support platform: {Application.platform}");
            }

            if (processInfo == null)
            {
                return null;
            }
            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;
            processInfo.RedirectStandardError = true;
            processInfo.RedirectStandardOutput = true;

            using (Process process = Process.Start(processInfo))
            {
                process.WaitForExit();

                return new Result(process);
            }
        }

        public static Result Execute(string fileName, string arguments)
        {
            arguments = arguments.Replace("\"", "\\\"");

            ProcessStartInfo start_info = new ProcessStartInfo(fileName, arguments);
            start_info.CreateNoWindow = true;
            start_info.UseShellExecute = false;
            start_info.RedirectStandardError = true;
            start_info.RedirectStandardOutput = true;

            using (Process process = Process.Start(start_info))
            {
                process.WaitForExit();

                return new Result(process);
            }
        }
    }
}
#endif